package co.yixiang.modules.websocket;


import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionPool {

    public static Map<String, Session> sessions = new ConcurrentHashMap<>();

    public static void close(String sessionId) {

        for (String userId : SessionPool.sessions.keySet()) {
            Session session = SessionPool.sessions.get(userId);
            if (sessionId.equals(session.getId())){
                SessionPool.sessions.remove(sessionId);
                break;
            }
        }
    }

    /**
     * 给指定的用户发送消息
     * @param sessionId
     * @param message
     */
    public void sendMessage(String sessionId , String message) {
        Session session = SessionPool.sessions.get(sessionId);
        session.getAsyncRemote().sendText(message);
    }

    /**
     * 发送给群消息
     * @param message
     */
    public static void sendMessage(String message) {
        for (String sessionid : SessionPool.sessions.keySet()) {
            Session session = SessionPool.sessions.get(sessionid);
            session.getAsyncRemote().sendText(message);
        }
    }

    /**
     * 测试发送给前端的list集合
     */
    public static void sendMessage(List<Integer> list) {
        for (String sessionid : SessionPool.sessions.keySet()) {
            Session session = SessionPool.sessions.get(sessionid);
            session.getAsyncRemote().sendObject(list);
        }
    }
}
